package com.zero.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import com.zero.user.User;
import com.zero.util.Codec;

/**
 * 客服端接收线程类 用于接收从服务端发送来的消息
 * 
 * @author Zero
 *
 */
public class ClientReceiveThread extends Thread {
	private ChatView chatView;
	private BufferedReader bufferedReader;

	public ClientReceiveThread(User user, ChatView chatView) throws IOException {
		this.chatView = chatView;
		bufferedReader = new BufferedReader(new InputStreamReader(user.getSocket().getInputStream()));
	}

	@Override
	public void run() {
		try {
			while (true) {
				String msg = Codec.decode(bufferedReader.readLine()); // 获取服务端发送的信息
				if ("repeat login".equals(msg)) {
					SwingUtilities.invokeLater(() -> {
						int result = JOptionPane.showOptionDialog(chatView, "重复登录！！！", "错误操作提示",
								JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
						if (result == JOptionPane.OK_OPTION || result == JOptionPane.CLOSED_OPTION) {
							System.exit(1);
						}
					});
				}
				chatView.setTextArea(msg);
			}
		} catch (IOException e) {
			SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(chatView, "接收服务端信息发生错误！\n可能是连接已断开", "错误",
					JOptionPane.ERROR_MESSAGE));
		}
	}
}
